import pickle
import base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request,user,response):
    # 合并请求用户的购物车数据，将未登录保存在cookie里的保存到redis中
    # 遇到cookie与redis中出现相同的商品时以cookie数据为主，覆盖redis中的数据
    # :param
    # request: 用户的请求对象
    # :param
    # user: 当前登录的用户
    # :param
    # response: 响应对象，用于清楚购物车cookie
    #获取ｃｏｏｋｉｅ中的购物车
    cookie_cart=request.COOKIES.get('cart')
    if not cookie_cart:
        return response

    #解析ｃｏｏｋｉｅ购物车数据
    cookie_cart = pickle.loads(base64.b64decode(cookie_cart.encode()))
    # cart[sku_id] = {
    #     'count': count,
    #     'selected': selected
    # }
    #获取ｒｅｄｉｓ中购物车数据
    redis_conn=get_redis_connection('cart')
    # reids_cart={'1':20,'2':5,}
    redis_cart=redis_conn.hgetall('cart_%s'%user.id)

    #用于保存最终购物车数据的字字典
    cart={}
    #将ｒｅｄｉｓ中购物车数据的键值对转换为整形
    # {16: {'selected': True, 'count': 1}
    # for sku_id,count in redis_cart.items():
    #     cart[int(sku_id)]=int[count]
    # 将redis中购物车数据的键值对转换为整型
    for sku_id, count in redis_cart.items():
        cart[int(sku_id)] = int(count)
    #记录ｒｅｄｉｓ勾选状态应该增加的ｓｋｕ_id
    redis_cart_selected_add = []
    #记录ｒｅｄｉｓ勾选状态中应该删除的ｓｋｕ_id
    redis_cart_selected_remove=[]

    #合并ｃｏｏｋｉｅ购物车与ｒｅｄｉｓ购物车　保存到ｃａｒｔ字典中
    # cart[sku_id] = {
    #     'count': count,
    #     'selected': selected
    # }
    for sku_id,count_selected_dict in cookie_cart.items():
        #处理商品数量 维护在ｒｅｄｉｓ中购物车数据数量的最终字典
        cart[sku_id]=count_selected_dict['count']
        #处理商品的勾选状态
        if count_selected_dict['selected']:
            redis_cart_selected_add.append(sku_id)
        else:
            redis_cart_selected_remove.append(sku_id)
    #执行ｒｅｄｉｓ操作
    if cart:
        pl = redis_conn.pipeline()
        #设置ｈａｓｈ类型
        pl.hmset('cart_%s' % user.id, cart)
        if redis_cart_selected_add:
            pl.sadd('cart_selected_%s' % user.id, *redis_cart_selected_add)
        if redis_cart_selected_remove:
            pl.srem('cart_selected_%s' % user.id, *redis_cart_selected_remove)
        pl.execute()

    response.delete_cookie('cart')

    return response



